<template>
  <el-card v-loading="loading">
    <el-col :span="24">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" :label-width="$i18n.locale === 'en-US' ? '140px' : '160px'">
        <el-col :span="24">
          <el-col :span="6" v-for="(o, index) in tplList" :key="o.tmpCode" :style="index%4=== 0 ? 'padding-top: 10px;' : 'padding-top: 10px;padding-left: 20px;'">
            <el-card :body-style="{ padding: '0px' }">
              <el-popover
                placement="right"
                title=""
                trigger="click">
                <img :src="o.picture" style="height: 300px;width: 750px" />
                <img slot="reference" :src="o.picture" :alt="o.tmpName" style="height: 100px;width: 250px">
              </el-popover>
              <div style="padding: 14px;">
                <el-radio v-model="dataForm.tplCategory" :label="o.tmpCode"> {{o.tmpName}}</el-radio>
              </div>
            </el-card>
          </el-col>
        </el-col>
        <el-col :span="24" style="padding-top: 20px;">
          <el-form-item :label="$t('genTable.genJavaDir')" prop="genJavaDir">
            <!--文本框-->
            <el-input v-model="dataForm.genJavaDir"
                      :placeholder="$t('genTable.genJavaDir')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('genTable.genUiDir')" prop="genUiDir">
            <!--文本框-->
            <el-input v-model="dataForm.genUiDir"
                      :placeholder="$t('genTable.genUiDir')" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-form>
    </el-col>
    <table-template v-if="tableTemplateVisible" ref="tableTemplate" @setTemplateList="setTemplateList"></table-template>
  </el-card>
</template>

<script>
import debounce from 'lodash/debounce'
import TableTemplate from './tableTemplate'
export default {
  data () {
    return {
      loading: false,
      tableTemplateVisible: false,
      tplList: [],
      dataForm: {
        id: '',
        sourceCode: '',
        genJavaDir: '',
        genUiDir: '',
        genType: 'override',
        options: '',
        tplCategory: ''
      }
    }
  },
  components: {
    TableTemplate
  },
  computed: {
    dataRule () {
      return {
        tplCategory: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        genJavaDir: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        genUiDir: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.init()
  },
  methods: {
    init () {
      this.$refs['dataForm'].resetFields()
      if (this.dataForm.tableName) {
        this.loading = true
        this.$nextTick(() => {
          this.getInfo()
        })
      }
    },
    // 获取信息
    getTempList (tmpType) {
      this.$http.get(`/gen/genTableType/list?tmpType=${tmpType}`).then(({ data: res }) => {
        this.loading = false
        if (res.code !== 0) {
          return false
        }
        this.tplList = res.data
        if (this.$xeutils.isEmpty(this.dataForm.tplCategory) && this.tplList.length > 0) {
          this.dataForm.tplCategory = this.tplList[0].tmpCode
        }
      }).catch(() => {})
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/gen/genTable/genInfo?dsCode=${this.dataForm.sourceCode}&tableName=${this.dataForm.tableName}`).then(({ data: res }) => {
        this.loading = false
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
        let tmpType = ''
        if (res.data.childTableCode === null || res.data.childTableCode === '') {
          tmpType = 'single'
        } else {
          tmpType = 'parent'
        }
        this.getTempList(tmpType)
      }).catch(() => {})
    },
    override () {
      this.dataForm.genType = 'override'
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$confirm('确定要生成代码并进行覆盖原文件', '提示', {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }).then(() => {
          this.tableTemplateVisible = true
          this.$nextTick(() => {
            this.$refs.tableTemplate.templateType = this.dataForm.tplCategory
            this.$refs.tableTemplate.init()
          })
        })
      })
    },
    download () {
      this.dataForm.genType = 'download'
      this.$confirm('确定要生成代码并下载', '提示', {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(() => {
        this.loading = true
        this.$http.get(`/gen/genTableTemplate/listBytemplateType?templateType=${this.dataForm.tplCategory}`).then(({ data: res }) => {
          this.loading = false
          if (res.code !== 0) {
            return false
          }
          if (res.data.length <= 0) {
            return this.$message.error('没有找到对应的代码生成模板文件')
          }
          this.dataForm.templateList = res.data
          this.dataFormSubmitHandle()
        })
      })
    },
    setTemplateList (tempList) {
      this.dataForm.templateList = tempList
      this.dataFormSubmitHandle()
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$http.put('/gen/genTable/', this.dataForm).then(({ data: res }) => {
        if (res.code !== 0) {
          return false
        }
        // 判断是否需要下载文件
        if (this.dataForm.genType === 'download') {
          this.downloadFile(res.data.fileName, res.data.base64Content)
        }
        this.$message({
          message: this.$t('prompt.success'),
          type: 'success',
          duration: 500,
          onClose: () => {
            this.$emit('setActiveName', 'close', this.dataForm.id)
          }
        })
      }).catch(() => {})
    }, 1000, { 'leading': true, 'trailing': false }),
    // 下载
    downloadFile (fileName, content) {
      var aLink = document.createElement('a')
      var blob = this.base64ToBlob(content)
      var evt = document.createEvent('HTMLEvents')
      evt.initEvent('click', true, true)
      aLink.download = fileName
      aLink.href = URL.createObjectURL(blob)
      aLink.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }))
    },
    // base64转blob
    base64ToBlob (code) {
      var parts = code.split(';base64,')
      var contentType = parts[0].split(':')[1]
      var raw = window.atob(parts[1])
      var rawLength = raw.length
      var uInt8Array = new Uint8Array(rawLength)
      for (var i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i)
      }
      return new Blob([uInt8Array], { type: contentType })
    }
  }
}
</script>
